package neo.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import neo.model.Hardware;

@Repository("hardwareDao")
public class HardwareDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	/**
	 * @param devId 设备ID
	 * @return 受影响行数
	 */
	public int add(Hardware hardware,Integer devId) {
		String sql="insert into t_hardware values(null,?,?,?,?,?,?,?,?,?)";
		return jdbcTemplate.update(sql,new Object[] {
				devId,
				hardware.getMac(),
				hardware.getIp(),
				hardware.getMotherboard(),
				hardware.getCpu(),
				hardware.getRam(),
				hardware.getRom(),
				hardware.getOs(),
				hardware.getPcName()
		});
	}
	
	public int update(Hardware hardware){
		String sql="UPDATE `t_hardware` SET `mac`=?, `ip`=?, `motherboard`=?, `cpu`=?, `ram`=?, `rom`=?, `os`=?, `pcName`=? WHERE (`devId`=?)";
		return jdbcTemplate.update(sql,new Object[]{
				hardware.getMac(),
				hardware.getIp(),
				hardware.getMotherboard(),
				hardware.getCpu(),
				hardware.getRam(),
				hardware.getRom(),
				hardware.getOs(),
				hardware.getPcName(),
				
				hardware.getDevId()
		});
	}
	
	public Hardware loadById(Integer devId) {
		StringBuffer sb = new StringBuffer("select * from t_hardware where devId=?");
		Hardware hardware = jdbcTemplate.queryForObject(sb.toString(),new Object[]{devId},new RowMapper<Hardware>(){

			@Override
			public Hardware mapRow(ResultSet rs, int arg1) throws SQLException {
				return hardwareMapRow(rs);
			}
			
		});
		return hardware;
	}
	
	public Integer haveDid(Integer devId){
		StringBuffer sb=new StringBuffer("select count(*) from t_hardware where devId = ?");
		Integer sum = 0;
		try {
			sum = jdbcTemplate.queryForObject(sb.toString(),new Object[]{devId}, Integer.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return sum;
	}
	/**
	 * 查询结果映射对象
	 */
	private Hardware hardwareMapRow(ResultSet rs)throws SQLException{
		Hardware hw = new Hardware();
		
		hw.setId(rs.getInt("id"));
		hw.setDevId(rs.getInt("devId"));
		hw.setMac(rs.getString("mac"));
		hw.setIp(rs.getString("ip"));
		hw.setMotherboard(rs.getString("motherboard"));
		hw.setCpu(rs.getString("cpu"));
		hw.setRam(rs.getString("ram"));
		hw.setRom(rs.getString("rom"));
		hw.setOs(rs.getString("os"));
		hw.setPcName(rs.getString("pcName"));
		
		return hw;
	}

}
